import { $ } from './library/jquery.js';
import cookie from './library/cookie.js';


$(function () {

    // 通过search获得商品id
    let id = location.search.split('=')[1];
    // 通过ajax获取对应id的product数据
    $.ajax({
        type: "get",
        url: "../../interface/getItem.php",
        data: {
            id: id
        },
        dataType: "json",
        success: function (res) {
            console.log(res);
            let details = JSON.parse(res.details);
            let pic = JSON.parse(res.picture);
            let version = JSON.parse(res.version);
            if (res.num == "该地区暂时缺货") $('.intocart').html("立即预约");
            $('title').html(res.title + '--小米商城');
            $('.main-fixed-container>h2,.main-header-container>h2,.main-info-right>h2').html(res.title);
            $('.main-info-right>p>span').first().html(details[0]).next().html(details[1]);
            $('.exist').html(res.num);
            $('.main-info-banner>img').attr('src', pic[1].src);
            if (version[0].suit) {
                $('.choose-product').html(res.title + ' ' + version[0].version + ' ' + version[0].color[0] + '' + version[0].suit[0]);
            } else {
                $('.choose-product').html(res.title + ' ' + version[0].version + ' ' + version[0].color[0]);
            }
            let chooseVersion = '',
                choosePrice = '',
                chooseColor = '',
                chooseSuit = '';
            version.forEach((elm, i) => {
                chooseVersion += `<div>${elm.version}</div>`;
                choosePrice += `<span class="hide" data-index=${i}>${elm.price}元</span>`;
                elm.color.forEach(val => {
                    chooseColor += `<div class="hide" data-index=${i}>${val}</div>`;
                });
                if (elm.suit) {
                    elm.suit.forEach(val => {
                        chooseSuit += `<div class="hide" data-index=${i}>${val}</div>`;
                    });
                } else {
                    $('.main-info-suit').remove();
                }
            });
            $('.main-info-version>div').append(chooseVersion).children().first().addClass('active-select');
            $('.main-info-color>div').append(chooseColor).children().first().addClass('active-select');
            $('.main-info-color>div').children('[data-index=0]').removeClass('hide');
            $('.main-info-suit>div').append(chooseSuit).children().first().addClass('active-select');
            $('.main-info-suit>div').children('[data-index=0]').removeClass('hide');
            $('.choose-price').append(choosePrice).children('[data-index=0]').removeClass('hide');
        }
    });

    // 事件委托 点击切换active-select
    $('.main-info-version').on('click', '.main-info-choose>div', function () {
        $(this).addClass('active-select').siblings().removeClass('active-select');
        let tmp = $(this).index();
        $(`.main-info-color .main-info-choose>div[data-index!=${tmp}]`).addClass('hide').removeClass('active-select');
        $(`.main-info-color .main-info-choose>div[data-index=${tmp}]`).removeClass('hide').first().addClass('active-select');
        $(`.main-info-suit .main-info-choose>div[data-index!=${tmp}]`).addClass('hide').removeClass('active-select');
        $(`.main-info-suit .main-info-choose>div[data-index=${tmp}]`).removeClass('hide').first().addClass('active-select');
        $('.choose-price').children(`[data-index=${tmp}]`).removeClass('hide').siblings().addClass('hide');
        let temp = $('title').html().slice(0, -6);
        $('.main-info-choose>div[class=active-select]').each((i, el) => {
            temp += ' ' + $(el).html();
        });
        $('.choose-product').html(temp);
    });

    $('.main-info-color,.main-info-suit').on('click', '.main-info-choose>div', function () {
        $(this).addClass('active-select').siblings().removeClass('active-select');
        let temp = $('title').html().slice(0, -6);
        $('.main-info-choose>div[class=active-select]').each((i, el) => {
            temp += ' ' + $(el).html();
        });
        $('.choose-product').html(temp);
    });

    // 鼠标hover效果
    $(document).on('mousemove', '.main-info-choose>div', function () {
        $(this).css({
            border: "1px solid #ff6700",
            color: "#ff6700"
        });
    });
    $(document).on('mouseout', '.main-info-choose>div', function () {
        $(this).css({
            border: "",
            color: ""
        });
    });

    // 购物车cookie
    $('.intocart').on('click', function () {
        addItem(id, $('.choose-price>span[class!=hide]').html().slice(0, -1), $('.choose-product').html(), 1);
        alert('加入购物车成功');
    });

    function addItem(id, price, title, num = 1) {
        let shop = cookie.get('shop');
        let product = {
            'id': id,
            'price': price,
            'title': title,
            'num': num
        }
        if (shop) {
            shop = JSON.parse(shop);
            if (shop.some(el => el.id == id)) {
                let _index = shop.findIndex(elm => elm.id == id);
                let count = parseInt(shop[_index].num);
                count += parseInt(num);
                shop[_index].num = count;
            } else {
                shop.push(product);
            }
        } else {
            shop = [];
            shop.push(product);
        }
        cookie.set('shop', JSON.stringify(shop), 1);
    }

    // // 购物车数据请求
    $('.header-cart').one('mouseenter', function () {
        let shop = cookie.get('shop');
        if (shop && shop != "[]") {
            $('.header-cart-empty').addClass('hide');
            $('.hcp-total').removeClass('hide');
            shop = JSON.parse(shop);
            let idList = shop.map(el => el.id).join();
            $.ajax({
                type: "get",
                url: "../../interface/getItems.php",
                data: {
                    idList: idList
                },
                dataType: "json",
                success: function (res) {
                    // console.log(res);
                    let tmp = '';
                    let price = 0;
                    res.forEach(elm => {
                        let pic = JSON.parse(elm.picture);
                        tmp += `
                            <div class="hcp-box">
                                <img src="${pic[0].src}"
                                    alt="">
                                <a href="./product.html?id=${elm.id}">${elm.title}</a>
                                <div>
                                <span class="hcp-price">${elm.price}</span>元
                                ×
                                <span class="hcp-num">1</span>
                                </div>
                            </div>`;
                        price += +elm.price;
                    });
                    $('.hcp-total').before(tmp);
                    $('.hcp-total-num>span').html($('.hcp-box').length);
                    $('.hcp-total-price>span').first().html(price);
                }
            });
        }
    });


    // 通用
    $('input').on({
        'focus': function () {
            $(this).parent().children().addClass('input-focus');
        },
        'blur': function () {
            $(this).parent().children().removeClass('input-focus');
        }
    });

    if (cookie.get('username')) {
        $('.header-mine').removeClass('hide');
        $('.header-login').addClass('hide');
        $('#username').html(cookie.get('username'));
    };
    $('#loginout').on('click', function () {
        cookie.remove('isLogined');
        cookie.remove('username');
        location.reload();
    });


    $('.header-search>input').on('focus', function () {
        $('.search-list').removeClass('hide');
    });

    $('.header-search>input').on('blur', function () {
        $('.search-list').addClass('hide');
    });
    // 头部

    // navslidedown效果
    let headerNavTimer = null;
    $('.header-nav2>div').first().hover(function () {
        if (headerNavTimer) {
            clearTimeout(headerNavTimer);
        }
        $('.header-list-container').slideDown(400);
    }, function () {
        headerNavTimer = setTimeout(() => {
            $('.header-list-container').slideUp(400);
        }, 300);
    });
    $('.header-list-container').hover(function () {
        if (headerNavTimer) {
            clearTimeout(headerNavTimer);
        }
    }, function () {
        headerNavTimer = setTimeout(() => {
            $('.header-list-container').slideUp(400);
        }, 300);
    });

    // 切换标签页
    $('.header-nav2>div').first().on('mousemove', function (ev) {
        let tmp = $(ev.target).attr('data-index');
        $(`.header-list[data-index=${tmp}]`).removeClass('hide');
        $(`.header-list[data-index!=${tmp}]`).addClass('hide');
    });

    // placeholder切换
    let placeholderList = ['【以旧换新】至高补贴3000元', '电视', '家电', '手机', '个护', '智能', '小米11', '空调', '洗衣机', '红米'];
    let placeholderListIndex = 1;
    setInterval(() => {
        $('.header-search>input').attr('placeholder', placeholderList[placeholderListIndex]);
        placeholderListIndex++;
        if (placeholderListIndex == placeholderList.length - 1) placeholderListIndex = 0;
    }, 4000);

    //

    //用户名下拉菜单

    let cartUsernameTimer = null;
    $('#username-box').hover(() => {
        if (cartUsernameTimer) clearTimeout(cartUsernameTimer);
        $('.username-list').stop(true, true);
        $('#username-box').css({
            backgroundColor: '#fff',
            color: '#ff6700'
        });
        $('.username-list').slideDown(200);
    }, () => {
        cartUsernameTimer = setTimeout(() => {
            $('.username-list').slideUp(200);
            $('#username-box').css({
                backgroundColor: '',
                color: ''
            });
        }, 200);
    });
    $('.username-list').hover(() => {
        if (cartUsernameTimer) clearTimeout(cartUsernameTimer);
    }, () => {
        cartUsernameTimer = setTimeout(() => {
            $('.username-list').slideUp(200);
            $('#username-box').css({
                backgroundColor: '',
                color: ''
            });
        }, 200);
    });

    // 购物车下拉菜单
    let cartBoxTimer = null;
    $('.header-cart').hover(() => {
        if (cartBoxTimer) clearTimeout(cartBoxTimer);
        $('.header-cart-box').stop(true, true);
        $('.header-cart-box').slideDown(200);
        $('.header-cart').css({
            backgroundColor: '#fff',
            color: '#ff6700'
        });
    }, () => {
        cartBoxTimer = setTimeout(() => {
            $('.header-cart-box').slideUp(200);
            $('.header-cart').css({
                backgroundColor: '',
                color: ''
            });
        }, 200);
    });
    $('.header-cart-box').hover(() => {
        if (cartBoxTimer) clearTimeout(cartBoxTimer);
    }, () => {
        cartBoxTimer = setTimeout(() => {
            $('.header-cart-box').slideUp(200);
            $('.header-cart').css({
                backgroundColor: '',
                color: ''
            });
        }, 200);
    });


    // 吸顶
    $(window).on('scroll', function () {
        if ($('html').scrollTop() > 200) {
            if ($('.main-fixed').hasClass('hide')) {
                $('.main-fixed').slideDown(400);
                $('.main-fixed').removeClass('hide');
            }
        } else {
            if (!$('.main-fixed').hasClass('hide')) {
                $('.main-fixed').slideUp(400);
                $('.main-fixed').addClass('hide');
            }
        }
    });

    // 底部

    // logo变换
    setInterval(() => {
        $('.ff-active>img').toggleClass('hide');
    }, 1500);

    // 侧边栏
    $(window).on('scroll', function () {
        if ($('html').scrollTop() > innerHeight) {
            $('aside>a').last().removeClass('hide');
            $('aside').css('bottom', 70);
        } else {
            $('aside>a').last().addClass('hide');
            $('aside').css('bottom', 174);
        };
    });

    //回到顶部
    $('aside>a').last().on('click', function () {
        $('html').scrollTop() = 0;
    });

});